package com.example.run_game;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
import android.content.res.AssetManager;
import android.location.Location;
import android.util.Log;
 
public class XMLParser {
 
    // constructor
    public XMLParser() {
 
    }
 
    public String getXmlFromUrl(String url) {
        String xml = null;
 
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
 
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }
 
    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
 
            DocumentBuilder db = dbf.newDocumentBuilder();
 
            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 
 
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
 
            return doc;
    }
 
    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }
 
     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }

	public static ArrayList<Location> parseXMLRoute(FileInputStream fis) throws SAXException
	{
		ArrayList<Location> route = new ArrayList<Location>();
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
		    db = dbf.newDocumentBuilder();
		    InputSource bis = new InputSource(fis);
		    try {
		        Document doc = db.parse(bis);
		        System.out.println(doc.toString());
		        NodeList message = doc.getFirstChild().getChildNodes();
		        for (int i=0;i<message.getLength();i++)
		        {
		        	Node n = message.item(i);
		        	if (n.getNodeType() == Node.ELEMENT_NODE)
		        	{
			        	NodeList elems = n.getChildNodes();
			        	Location newLocation = new Location("");
				        for (int j=0;j<elems.getLength();j++)
				        {
				        	Node nowde = elems.item(j);
				        	if (nowde.getNodeName() != "#text")
				        	{	
					        	String name = nowde.getNodeName();
					        	String content = nowde.getTextContent();
					        	if (name.equals("Time"))
					        	{
					        		long t = Long.parseLong(content);
					        		newLocation.setTime(t);
					        	}
					        	else if (name.equals("Latitude"))
					        	{
					        		double d = Double.parseDouble(content);
					        		newLocation.setLatitude(d);
					        	}
					        	else if (name.equals("Longitude"))
					        	{
					        		double d = Double.parseDouble(content);
					        		newLocation.setLongitude(d);
					        	}
					        	else if (name.equals("Altitude"))
					        	{
					        		double d = Double.parseDouble(content);
					        		newLocation.setAltitude(d);
					        	}
				        	}
				        }
			        	route.add(newLocation);
		        	}
		        }
		    } catch (SAXException e) {
		        e.printStackTrace();
		        throw e;
		    } catch (IOException e) {
		        e.printStackTrace();
		    } catch (DOMException e) {
		        e.printStackTrace();
		    }
		} catch (ParserConfigurationException e1) {
		    e1.printStackTrace();
		}
		return route;
	}
	
	
	public static String[] parseXMLWeather(InputStream fis) throws SAXException
	{
		String[] weatherArray = {"","","","","",""};
		String weather_type = "";
		String weather_date = "";
		String temperature = "";
		String wind_direction= "";
		String wind_speed= "";
		String weather_code= "";
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
		    db = dbf.newDocumentBuilder();
		    InputSource bis = new InputSource(fis);
		    try {
		        Document doc = db.parse(bis);
		        NodeList message = doc.getFirstChild().getChildNodes();
		        for (int i=0;i<message.getLength();i++)
		        {
		        	Node n = message.item(i);
		        	//System.out.println("node name: "+n.getNodeName());
		        	if (n.getNodeType() == Node.ELEMENT_NODE)
		        	{
			        	NodeList elems = n.getChildNodes();

				        for (int j=0;j<elems.getLength();j++)
				        {
				        	Node nowde = elems.item(j);
				        	//System.out.println("elem name: "+nowde.getNodeName());
				        	//if (nowde.getNodeName() != "#text")
				        	//{	
					        	String name = nowde.getNodeName();
					        	String content = nowde.getTextContent();
					        	if (name.equals("yweather:wind"))
					        	{
					        		NamedNodeMap windAttr = nowde.getAttributes();
			        				Node dirNode = windAttr.getNamedItem("direction");
			        				Node speedNode = windAttr.getNamedItem("speed");
			        				wind_direction = dirNode.getTextContent();
			        				wind_speed = speedNode.getTextContent();
					        	}
				        		else if (name.equals("item"))
					        	{
					        		NodeList infoList = nowde.getChildNodes();
					        		for (int k=0;k<infoList.getLength();k++)
							        {
					        			Node noard = infoList.item(k);
					        			String noard_name = noard.getNodeName();
					        			String noard_content = noard.getTextContent();
					        			if (noard_name.equals("yweather:condition"))
					        			{
					        				NamedNodeMap conditionAttr = noard.getAttributes();
					        				Node textNode = conditionAttr.getNamedItem("text");
					        				Node tempNode = conditionAttr.getNamedItem("temp");
					        				Node dateNode = conditionAttr.getNamedItem("date");
					        				Node codeNode = conditionAttr.getNamedItem("code");
					        				weather_type = textNode.getTextContent();
					        				temperature = tempNode.getTextContent();
					        				weather_date = dateNode.getTextContent();
					        				weather_code = codeNode.getTextContent();
					        				//System.out.println("FOUND WEATHER CONDITION: "+weather_date+ " --- "+weather_type + " --- "+temperature+ " --- "+wind_direction+ " --- "+wind_speed);
					        			}
							        }
					        	}
				        	//}
				        }
		        	}
		        }
		    } catch (SAXException e) {
		        e.printStackTrace();
		        throw e;
		    } catch (IOException e) {
		        e.printStackTrace();
		    } catch (DOMException e) {
		        e.printStackTrace();
		    }
		} catch (ParserConfigurationException e1) {
		    e1.printStackTrace();
		}
		
		weatherArray[0] = weather_date;
		weatherArray[1] = weather_type;
		weatherArray[2] = temperature;
		weatherArray[3] = wind_direction;
		weatherArray[4] = wind_speed;
		weatherArray[5] = weather_code;
		
		return weatherArray;
	}
	
}